package com.zy.socket.practies;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @Author Gong
 * @Description 客户端给服务端发送文本，服务端会将文本转成大写在返回给客户端
 * @dATE 2021/12/19 10:41
 **/
public class Server2 {
    public static void main(String[] args) {
        InputStream inputStream = null;
        Socket accept =null;
        ServerSocket serverSocket =null;
        try {
             serverSocket = new ServerSocket(8989);
             accept = serverSocket.accept();
            System.out.println(accept);

            InputStream inputStream1 = accept.getInputStream();
            byte[] buff = new byte[1024];
            int len;
            String str = null;

            while ((len=inputStream1.read(buff)) > -1){
                str = new String(buff,0,len);
                str = str.toUpperCase();
            }
            accept.shutdownInput();
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write(str.getBytes(StandardCharsets.UTF_8));

            //方法2
//            InputStreamReader isr = new InputStreamReader(inputStream1);
//            Reader reader = new BufferedReader(isr);
//
//            OutputStream outputStream = accept.getOutputStream();
//
//            int len;
//            while ((len=reader.read()) > -1){
//                Character c = Character.toUpperCase((char)len);
//                System.out.println(c);
//                outputStream.write(c.toString().getBytes(StandardCharsets.UTF_8));
//            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
